package main

import (
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/canvas"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/layout"
	"fyne.io/fyne/v2/widget"
	"image/color"
	"unicode"

	"ZxDict/pkg/CETranslator"
	"ZxDict/pkg/ECTranslator"
)

var ce CETranslator.CETranslator

var FirstEntry *widget.Entry
var SecondEntry *widget.Entry

func getTranslatorComponent() *fyne.Container {
	input := widget.NewEntry()
	input.TextStyle.Monospace = true
	input.TextStyle.Bold = true
	input.Cursor()

	if FirstEntry == nil {
		FirstEntry = input
	} else {
		SecondEntry = input
	}
	input.SetPlaceHolder("Enter text to translate...")
	//input.SetMinRowsVisible(2)
	//input.Resize(fyne.NewSize(input.MinSize().Width, 10*input.MinSize().Height)) // 调整高度

	richText := widget.NewRichTextFromMarkdown("")
	richText.Wrapping = fyne.TextWrapWord

	input.OnSubmitted = func(word string) {
		var ss string
		if containsChinese(word) {
			ret := ce.Translate(word)
			if len(ret) == 0 {
				ss = "无法找到单词: " + word
			} else {
				ss = "*" + ret[0].EnglishInterpretation + "*"
			}
		} else {
			ret := ECTranslator.Translator(word)
			if len(ret) == 0 {
				ss = "无法找到单词: " + word
			} else {
				//t := ret[0]
				if nounTransList, exist := ret[0].Synset["n"]; exist {
					if len(nounTransList) != 0 {
						ss += "## 名词形式：\n"
						ss += nounTransList[0].Gloss
						ss += "\n"
					}
				}
				if verbTransList, exist := ret[0].Synset["v"]; exist {
					if len(verbTransList) != 0 {
						ss += "## 动词形式：\n"
						ss += verbTransList[0].Gloss
						ss += "\n"
					}
				}
			}
		}
		newRichText := widget.NewRichTextFromMarkdown(ss)
		richText.Segments = newRichText.Segments
		richText.Refresh()
	}

	// 添加一个占位符组件在输入框下方
	placeholder := canvas.NewRectangle(color.Transparent)
	placeholder.SetMinSize(fyne.NewSize(1, 20)) // 高度与输入法候选框相似
	return container.NewVBox(input, placeholder, richText)
}

func containsChinese(s string) bool {
	for _, r := range s {
		if unicode.Is(unicode.Han, r) {
			return true
		}
	}
	return false
}

func getTranslatorApp(myApp fyne.App) *container.TabItem {
	return container.NewTabItem("翻译", container.New(layout.NewGridLayoutWithColumns(2), getTranslatorComponent(), getTranslatorComponent()))
}
